import axios from 'axios'
import vue from 'vue'
import { getToken } from '@/utils/auth'

axios.interceptors.response.use(
	function(response) {
		return response
	},
	function(error) {
		// Do something with response error
		return Promise.reject(error)
	}
)
// 请求拦截器 带上token
axios.interceptors.request.use(
	function(config) {
		// 在发送请求之前做些什么，例如加入token
		let token = getToken()
		if (token != null && token != '') {
            config.headers.TOKEN = token
		}
		return config
	},
	function(error) {
		// 对请求错误做些什么
		return Promise.reject(error)
	}
)

/*
 * 封装请求方法
 */
const request = function(loadtip, query) {
	let loading
	if (loadtip) {
		loading = vue.prototype.$loading({
			lock: false,
			text: '正在加载中…',
			spinner: 'el-icon-loading',
			background: 'rgba(0, 0, 0, 0.5)',
		})
	}
	return axios
		.request(query)
		.then((res) => {
			if (loadtip) {
				loading.close()
			}
			if (res.data.code === 401) {
				  vue.prototype.$$router.push({ path: '/login' })
				return Promise.reject(res.data)
			} else if (res.data.code === 500) {
				return Promise.reject(res.data)
			} else if (res.data.code === 501) {
				return Promise.reject(res.data)
			} else if (res.data.code === 502) {
				  vue.prototype.$$router.push({ path: '/login' })
				return Promise.reject(res.data)
			} else {
				return Promise.resolve(res.data)
			}
		})
		.catch((e) => {
			if (loadtip) {
				loading.close()
			}
			vue.prototype.$message.error(e.message)
			return Promise.reject(e.message)
		})
}

//post请求  ----> json格式的post请求 无load
const post = function(url, params) {
	const query = {
		url: url,
		method: 'post',
		withCredentials: true, //跨域允许携带cookie
		timeout: 30000,
		data: params,
		headers: { 'Content-Type': 'application/json', 'request-ajax': true },
	}
	return request(false, query)
}

//post请求  ----> json格式的post请求 有load
const postWithLoadTip = function(url, params) {
	const query = {
		url: url,
		method: 'post',
		withCredentials: true,
		timeout: 30000,
		data: params,
		headers: { 'Content-Type': 'application/json', 'request-ajax': true },
	}
	return request(true, query)
}

//post请求  ----> json格式的post请求 有load
const postWithOutLoadTip = function(url, params) {
	const query = {
		url: url,
		method: 'post',
		withCredentials: true,
		timeout: 30000,
		data: params,
		headers: { 'Content-Type': 'application/json', 'request-ajax': true },
	}
	return request(false, query)
}

//Get请求
const get = function(url, params) {
	const query = {
		url: url,
		method: 'get',
		withCredentials: true,
		timeout: 30000,
		params: params,
		headers: { 'request-ajax': true },
	}
	return request(false, query)
}

//post请求  ----> 表单格式的post请求 有load
const form = function(url, params) {
	const query = {
		url: url,
		method: 'post',
		withCredentials: true,
		timeout: 30000,
		data: params,
		headers: {
			'Content-Type': 'multipart/form-data',
			'request-ajax': true,
		},
	}
	return request(false, query)
}

export { post, postWithLoadTip, postWithOutLoadTip, get, form }
